package com.chenfan.process.event.callback;

import com.chenfan.ccp.util.start.ApplicationContextUtil;
import com.chenfan.ccp.util.tool.JsonUtil;
import com.chenfan.process.biz.ApprovalInternalBiz;
import com.chenfan.process.dto.ApprovalCallBack;
import com.chenfan.process.entity.po.ApprovalPo;
import com.chenfan.process.entity.po.ApprovalTemplatePo;
import com.chenfan.process.entity.po.ProcessNotifyPo;
import com.chenfan.process.enums.ProcessNotifyTypeEnums;
import com.chenfan.process.service.ApprovalService;
import com.chenfan.process.service.ApprovalTemplateService;
import com.chenfan.process.service.ProcessNotifyService;
import com.chenfan.process.vo.ApprovalNodeVO;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author K
 * @date 2021/1/27
 */
@RefreshScope
@Component
public class TriggerCallbackListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ProcessNotifyService processNotifyService;
    @Autowired
    private ThirdCallback thirdCallback;
    @Autowired
    private ApprovalTemplateService approvalTemplateService;

    @SneakyThrows
    @Async("threadPoolTaskExecutor")
    @EventListener({TriggerCallbackEvent.class})
    public void onApplicationEvent(TriggerCallbackEvent event) {
        List<TriggerCallbackEventData> triggerCallbackEventDataList = event.getTriggerCallbackEventDataList();

        for(TriggerCallbackEventData callbackEvent: triggerCallbackEventDataList) {
            ApprovalCallBack approvalCallBack = callbackEvent.getApprovalCallBack();
            logger.info("开始回调审批:{}", JsonUtil.obj2String(callbackEvent));
            String token = callbackEvent.getToken();
            ApprovalPo approval = callbackEvent.getApprovalPo();
            ApprovalTemplatePo approvalTemplate = approvalTemplateService.getById(approval.getApprovalTemplateId());

            Integer notifyType = ProcessNotifyTypeEnums.URL.getIndex();
            switch (ProcessNotifyTypeEnums.resolve(notifyType)) {
                case DING_DING:
                case MQ:
                    break;
                case URL:
                    thirdCallback.getResponseByUrl(approvalCallBack.getServiceName(), "callback", approvalCallBack, token);
                    String property =
                            ApplicationContextUtil.getContext().getEnvironment().getProperty("feign.debug.enable");
                    boolean debug =
                            !StringUtils.isEmpty(approvalCallBack.getNextApprovalUserId()) && StringUtils.isEmpty(property);
                    // 可以产生.并且没有结束才存, 结束时已经是消息, 消息后续不统计检查
                    if (debug && approvalTemplate.needNotify() && !approval.isFinish()) {
                        String[] split = approvalCallBack.getNextApprovalUserId().split(",");
                        String[] names = approvalCallBack.getNextApprovalUserName().split(",");
                        for (int i = 0; i < split.length; i++) {
                            processNotifyService.save(ProcessNotifyPo.ofDefault(approvalCallBack.getApprovalId(), approval.getApprovalTemplateId(),
                                    Long.valueOf(split[i]), names[i]));
                        }
                    }
                    break;
                default:
            }
        }
    }
}
